package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.mallcai.bigdata.ladon.client.vo.ReportColumnVO;
import com.mallcai.bigdata.ladon.client.vo.ReportDataVO;
import com.mallcai.bigdata.ladon.datasource.RunInfoResult;
import com.mallcai.bigdata.ladon.dpl.entity.report.ReportColumn;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 13:06
 */
@Slf4j
@Service
@Order(800)
public class ProcessColumnVOPostHandler extends AbstractReportQueryPostHandler {

    @Override
    protected void postInternal(ReportQueryContext context) {
        RunInfoResult<ReportDataVO> result = context.getResult();
        Assert.notNull(result, "查询结果不能为空");

        ReportDataVO data = result.getData();
        if (data != null) {
            List<ReportColumnVO> columns = data.getColumns();
            if (CollectionUtils.isNotEmpty(columns)){
                List<ReportColumn> reportColumns = context.getInnerParam(ReportQueryConstants.KEY_REPORT_SQL_COLUMNS);
                Map<String, ReportColumn> reportColumnMap = reportColumns.stream().collect(Collectors.toMap(ReportColumn::getName, Function.identity()));
                columns.forEach(reportColumnVO -> {
                    ReportColumn reportColumn = reportColumnMap.get(reportColumnVO.getName());
                    if(reportColumn != null){
                        reportColumnVO.setShowName(reportColumn.getShowName());
                        reportColumnVO.setUnit(reportColumn.getUnit());
                        reportColumnVO.setDataType(reportColumn.getDataType());
                    }
                });
            }
        }
    }

}
